<script setup>
import {computed, reactive, ref, onMounted, toRaw} from 'vue';
import dayjs from 'dayjs'
import {message,Modal} from 'ant-design-vue'
import {userUserStore} from "@/stores/index.js";
import {setStuInfo} from './share.js'
import { cloneDeep } from 'lodash';
import 'dayjs/locale/zh-cn';
import {
  updateEducationExperience,
    addEducationExperience,
  deleteEducationExperience,
  getStuInfo,
} from "@/api/stu.js";
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import {getMajorStore} from "@/stores/modules/allMajor.js";
import {getSchoolStore} from "@/stores/modules/allSchool.js";

//选项列表 -- 职位
const majorPositionList = ref(getMajorStore().majorList);

const schoolNameList = ref(getSchoolStore().schoolList)

const qualificationsList = [
  { label:'初中及以下', value: '1'},
  { label:'高中', value: '2'},
  { label:'大专', value: '3'},
  { label:'本科', value: '4'},
  { label:'硕士', value: '5'},
  { label:'博士', value: '6'},
];

const structureList = [
  { label:'全日制', value: '0'},
  { label:'非全日制', value: '1'},
]

const formRef = ref()
const isAdd = ref(false)
const currentIndex = ref(null)
const placeholder1 = ref('主要描述在公司负责的工作，分点')

// 表单数据
const formData = reactive([]);

// // 备份原始数据，用于取消操作恢复
// let oldFormData = reactive([])

//初始化数据
onMounted(() =>{
  updateFormData()
})
//更新数据
const updateFormData = () =>{
  formData.splice(0)
  Object.assign(formData, userUserStore().userInfo.educationExperiences||[])
}

let FormattedTime = ref([])
const getFormattedTime = () =>{
  if (formData[currentIndex.value].schoolTimeRange.length===0) return
  FormattedTime.value = formData[currentIndex.value].schoolTimeRange.map(date => {
    return dayjs(date).format(dateFormat)
  })
}

const transDayTime = () =>{
  if (formData[currentIndex.value].schoolTimeRange.length===0) return
  formData[currentIndex.value].schoolTimeRange = formData[currentIndex.value].schoolTimeRange.map(date => {
    return dayjs(date)
  })
}

// 添加新职位表单
const onAdd = async() => {
  formData.push(
      {
        schoolName: null,
        majorName: null,
        schoolTimeRange: [],
        schoolContent: null,
        academicStructure: null,
        qualification: null,
        ranking: null,
      })
  currentIndex.value = formData.length - 1;
  isAdd.value = true
}

//编辑
const onEdit = (index) => {
  currentIndex.value = index
  transDayTime()
};

// 删除职位表单
const onDelete = (index) => {
  Modal.confirm({
    title: '确定删除该职位吗？',
    content: '删除后将无法恢复',
    okText: '确定',
    cancelText: '取消',
    async onOk() {  // 将异步处理单独放在外部
      try {
        const resDel = await deleteEducationExperience({
          educationExperienceId: formData[index].educationExperienceId
        })  // 直接等待删除操作
        if (resDel.data.code === 200) {
          message.success("删除成功");
          const resGet = await setStuInfo();  // 等待更新学生信息
          if (resGet === 200) {
            updateFormData()
          }
        } else {
          message.error(resDel.data.message);
        }
      } catch (err) {
        message.error(err.message || "删除失败");
      }
    },
  });
};

// 确认
const submit = async () => {
  getFormattedTime()
  await formRef.value.validate().then(async () => {
    try {
      const formDataToSubmit = { ...formData[currentIndex.value], schoolTimeRange: FormattedTime.value }
      const resUpdate = (isAdd.value)?(await addEducationExperience(formDataToSubmit))
          : (await updateEducationExperience(formDataToSubmit))
      currentIndex.value = null;
      if(isAdd.value) isAdd.value = false
      if (resUpdate.data.code === 200) {
        message.success("提交成功");

        // 更新学生信息
        const resGet = await setStuInfo();  // 等待更新学生信息
        if ( resGet === 200) {
          updateFormData()
        }
      } else {
        message.error(resUpdate.data.message);
      }
    } catch (err) {
      message.error(err.message || "提交失败");
    }
  }).catch(err => {
    // 处理验证失败情况
    message.error("请检查表单内容是否填写完整");

  });
};

// 取消编辑，恢复到原始状态
const cancel = async () => {
  const resGet = await setStuInfo();  // 等待更新学生信息
  if ( resGet === 200) {
    updateFormData()
  }
  currentIndex.value=null
};

const qualificationLabel = (index) => {
  return qualificationsList.find(item => item.value === formData[index]?.qualification)?.label;
}

// 样式
const selectStyle = {
  width: "100%",
  height: "40px"
};

const disabledDate = current => {
  return current && current >= dayjs().endOf('day');
};

const dateFormat = 'YYYY/MM';

const rules = computed(() => ({
  schoolName: [
    {
      required: true,
      message: "请选择学校",
      trigger: "change",
    },
  ],
  majorName: [
    {
      required: formData[currentIndex.value]?.qualification >= 3,
      message: "请选择专业",
      trigger: "change",
    },
  ],
  schoolTimeRange: [
    {
      required: true,
      message: "请选择时间",
      trigger: "change",
    },
  ],
  schoolContent: [
    {
      required: true,
      message: "请填写详细内容",
      trigger: "change",
    },
  ],
  academicStructure: [
    {
      required: formData[currentIndex.value]?.qualification >= 3,
      message: "请选择学制",
      trigger: "change",
    },
  ],
  ranking: [
    {
      required: formData[currentIndex.value]?.qualification >= 3,
      message: "请填写排名",
      trigger: "change",
    },
  ],
  qualification: [
    {
      required: true,
      message: "请选择学历",
      trigger: "change",
    },
  ],
}));


dayjs.locale('zh-cn');
</script>

<template>
  <!-- 编辑模式 -->
  <div class="edit-container"  v-if="currentIndex !== null">
    <h4 style="height: 40px; margin-top: 0;">添加教育经历</h4>
    <a-form layout="vertical" :rules="rules" ref="formRef" :model="formData[currentIndex]">
      <a-row :gutter="80">
        <a-col :span="12">
          <a-form-item label="学校名称" name="schoolName">
            <a-select
                v-if="formData[currentIndex].qualification>=3"
                v-model:value="formData[currentIndex].schoolName"
                :disabled="!formData[currentIndex].qualification"
                show-search
                placeholder="请选择学校"
                :options="schoolNameList"
                size="large"
                :style="selectStyle"
            ></a-select>
            <a-input
                v-else
                v-model:value="formData[currentIndex].schoolName"
                :disabled="!formData[currentIndex].qualification"
                :style="selectStyle"
                placeholder="请输入学校名称"
                size="large"
            />
          </a-form-item>
          <a-form-item label="专业" name="majorName">
            <a-select
                :disabled="!(formData[currentIndex].qualification>=3||formData[currentIndex].qualification==='')"
                v-model:value="formData[currentIndex].majorName"
                :style="selectStyle"
                show-search
                :options="majorPositionList"
                placeholder="示例:软件工程"
                size="large"
            >
            </a-select>
          </a-form-item>
          <a-form-item label="请选择学制" v-if="formData[currentIndex].qualification>=3" name="academicStructure">
            <a-select
                v-model:value="formData[currentIndex].academicStructure"
                :style="selectStyle"
                show-search
                :options="structureList"
                placeholder="请选择学制"
                size="large"
            >
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="请选择学历" name="qualification">
            <a-select
                v-model:value="formData[currentIndex].qualification"
                :style="selectStyle"
                :options="qualificationsList"
                placeholder="请选择学历"
                size="large"
            >
            </a-select>
          </a-form-item>
          <a-form-item label="时间段" name="schoolTimeRange">
            <a-range-picker
                :locale="locale"
                v-model:value="formData[currentIndex].schoolTimeRange"
                picker="month"
                :style="selectStyle"
                :format="dateFormat"
                :disabled-date="disabledDate"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-form-item label="教育经历(选填)" name="schoolContent" :required="false">
        <a-textarea
            v-model:value="formData[currentIndex].schoolContent"
            show-count :maxlength="1600"
            :autosize="{ minRows: 8, maxRows: 10 }"
            :placeholder="placeholder1" />
      </a-form-item>
      <a-form-item label="请输入成绩" v-if="formData[currentIndex].qualification>=3" name="ranking">
        <a-input
            v-model:value="formData[currentIndex].ranking"
            :style="selectStyle"
            placeholder="请输入成绩"
            size="large"
        >
        </a-input>
      </a-form-item>
      <a-row>
        <a-col :span="11" :push="13">
          <a-form-item>
            <!-- 按钮 -->
            <div class="button-item">
              <a-button size="large" @click="cancel">取消</a-button>
              <a-button type="primary" size="large" @click="submit">确认</a-button>
            </div>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </div>

  <!-- 默认模式 -->
  <div class="default-container"  v-else>
    <div style="display: flex; align-items: center;justify-content: space-between">
      <div style="display: flex; align-items: center;">
        <div class="title"></div>
        <h2>教育经历</h2>
      </div>
      <div class="add-info" @click="onAdd">添加</div>
    </div>
    <h4 v-if="formData.length===0">
      添加教育经历
    </h4>
    <div class="user-info" v-for="(item, index) in formData" :key="index" v-if="formData.length!==0">
      <div class="user-info-title">
        <span v-if="item.schoolName">{{item.schoolName}}</span>
        <span v-if="item.academicStructure">{{item.academicStructure === 0? '全日制': '非全日制' }}</span>
        <span  v-if="item.schoolTimeRange.length!==0">
          {{ item.schoolTimeRange[0] }} - {{ item.schoolTimeRange[1] }}
        </span>
      </div>
      <div class="user-info-delicate">
        <span v-if="item.qualification">{{ qualificationLabel(index) }}</span>
        <span v-if="item.majorName" style="gap:20px;color: #b8b8bb"></span>
        <span v-if="item.majorName">{{item.majorName}}</span>
        <span v-if="item.majorName" style="gap:20px;color: #b8b8bb"></span>
        <span v-if="item.ranking">排名：{{item.ranking}}</span>
      </div>
      <a-row class="user-info-row" v-if=" item.schoolContent" v-html="`内容：${item?.schoolContent.replace(/\n/g, '<br>')}`"></a-row>
      <a-space direction="vertical" class="change-container">
        <a-button type="link" @click="onEdit(index)" class="edit-info">编辑</a-button>
   <a-button type="link" @click="onDelete(index)" class="delete-info">删除</a-button>
      </a-space>
    </div>
  </div>
</template>

<style scoped>
.edit-container {
  width: 100%;
  height: 100%;
  background-color: #f5f6fa;
  padding: 20px;
  border-radius: 10px;
}

.default-container {
  width: 100%;
  padding: 20px;
}

.title {
  width: 4px;
  height: 25px;
  background: #00bebd;
  border-radius: 3px;
  margin-right: 10px;
}

.button-item {
  display: flex;
  margin-left: 100px;
  justify-content: space-around;
}

a-input-number {
  flex: 1;
}

.user-info {
  margin-left: 3px;
  margin-top: 10px;
  display: grid;
  cursor: pointer;
  padding: 10px;
  position: relative;
  min-height: 70px;
}

.user-info-title {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  >span{
    color: #8c8c8c;
    font-size: 13px;
  }
  >span:nth-child(1){
    font-size: 20px;
  }
}

.user-info-delicate {
  display: flex;
  gap: 20px;
  align-items: center;
  margin: 3px 0;
}

.user-info-row {
  word-wrap: break-word;
  word-break: break-all;
  padding: 5px 0;
}

.title {
  width: 4px;
  height: 25px;
  background: #00bebd;
  border-radius: 3px;
  margin-top: -8px;
  margin-right: 10px;
}

.change-container {
  justify-self: end;
  position: absolute;
  bottom: 5px;
}

.add-info {
  display: flex;
  font-size: 14px;
  color: #595959;
  cursor: pointer;
}

.user-info:hover {
  background-color: #e6f7ff;
}
</style>

